package com.ms.log.factory;

import com.ms.log.context.LogContextInitializer;
import com.ms.log.context.LoggerContext;
import com.ms.log.logger.DefaultLogger;
import com.ms.log.logger.Logger;

/**
 * @author zdh
 */
public class DefaultLoggerFactory implements LoggerFactory {

    private LoggerContext loggerContext;
    public static final String DOT = ".";

    public DefaultLoggerFactory() {
        //DefaultLoggerFactory，直接调用配置解析的方法，并获取loggerContext
        LogContextInitializer.autoConfig();
        loggerContext = LogContextInitializer.getDefaultLoggerContext();
    }


    @Override
    public Logger getLogger(Class<?> clazz) {
        return getLogger(clazz.getName());
    }

    @Override
    public Logger getLogger(String name) {
        Logger logger = loggerContext.getLogger(name);
        if(logger == null){
            logger = newLogger(name);
        }
        return logger;
    }

    @Override
    public Logger newLogger(String name) {
        DefaultLogger logger = new DefaultLogger(name);
        logger.setLoggedName(name);
        Logger parent = null;
        //拆分包名，向上查找parent logger
        for (int i = name.lastIndexOf(DOT); i >= 0; i = name.lastIndexOf(DOT,i-1)) {
            String parentName = name.substring(0,i);
            parent = loggerContext.getLogger(parentName);
            if(parent != null){
                break;
            }
        }
        if(parent == null){
            parent = loggerContext.getRoot();
        }
        logger.setParent(parent);
        logger.setLoggerContext(loggerContext);
        return logger;
    }
}
